<template>
  <div class="carbon-emission-compare-container">
    <el-row :gutter="20">
      <!-- 柱状图对比区域 -->
      <el-col :span="24">
        <div class="chart-container">
          <div id="barChart" style="width: 100%; height: 400px;"></div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 左侧工程数据 -->
      <el-col :span="12">
        <div class="data-container">
          <h3 class="project-title">{{ projectNames[0] || '工程一' }}</h3>

          <!-- 总体指标表格 -->
          <el-table :data="overallData1" style="width: 100%; margin-bottom: 20px;" border>
            <el-table-column prop="item" label="总体指标" width="180"></el-table-column>
            <el-table-column prop="value" label="数值"></el-table-column>
          </el-table>

          <!-- 强度指标表格 -->
          <el-table :data="intensityData1" style="width: 100%;" border>
            <el-table-column prop="item" label="强度指标" width="180"></el-table-column>
            <el-table-column prop="value" label="数值"></el-table-column>
          </el-table>
        </div>
      </el-col>

      <!-- 右侧工程数据 -->
      <el-col :span="12">
        <div class="data-container">
          <h3 class="project-title">{{ projectNames[1] || '工程二' }}</h3>

          <!-- 总体指标表格 -->
          <el-table :data="overallData2" style="width: 100%; margin-bottom: 20px;" border>
            <el-table-column prop="item" label="总体指标" width="180"></el-table-column>
            <el-table-column prop="value" label="数值"></el-table-column>
          </el-table>

          <!-- 强度指标表格 -->
          <el-table :data="intensityData2" style="width: 100%;" border>
            <el-table-column prop="item" label="强度指标" width="180"></el-table-column>
            <el-table-column prop="value" label="数值"></el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { listAll } from '@/api/business/engineering'

export default {
  name: 'CarbonEmissionCompare',
  data() {
    return {
      // 柱状图实例
      barChart: null,
      // 工程名称
      projectNames: [],
      // 工程一数据
      overallData1: [
        { item: '工程总体碳排放', value: '0 tCO₂e' },
        { item: '勘察设计', value: '0' },
        { item: '建材生产运输', value: '0' },
        { item: '施工阶段', value: '0' },
        { item: '运营维护', value: '0' },
        { item: '拆除处置', value: '0' },
      ],
      intensityData1: [
        { item: '强度指标', value: '0 kgCO₂e/(m²·a)' }
      ],
      // 工程二数据
      overallData2: [
        { item: '工程总体碳排放', value: '0 tCO₂e' },
        { item: '勘察设计', value: '0' },
        { item: '建材生产运输', value: '0' },
        { item: '施工阶段', value: '0' },
        { item: '运营维护', value: '0' },
        { item: '拆除处置', value: '0' },
      ],
      intensityData2: [
        { item: '强度指标', value: '0 kgCO₂e/(m²·a)' }
      ],
      // 柱状图配置
      chartOption: {
        title: {
          text: '工程碳排放对比',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['工程一', '工程二'],
          top: '10%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['勘察设计', '建材生产运输', '施工阶段', '运营维护', '拆除处置']
        },
        yAxis: {
          type: 'value',
          name: '碳排放量 (KgCO₂e)'
        },
        series: [
          {
            name: '工程一',
            type: 'bar',
            data: [0, 0, 0, 0, 0],
            itemStyle: {
              color: '#5470c6'
            }
          },
          {
            name: '工程二',
            type: 'bar',
            data: [0, 0, 0, 0, 0],
            itemStyle: {
              color: '#91cc75'
            }
          }
        ]
      }
    }
  },
  mounted() {
    this.fetchData()
    // 响应窗口大小变化
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.barChart) {
      this.barChart.dispose();
      this.barChart = null;
    }
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 获取数据
    async fetchData() {
      try {
        // 获取路由参数
        const engineeringIdList = this.$route.query.engineeringIdList ?
          this.$route.query.engineeringIdList.split(',') : []
        const projectIdList = this.$route.query.projectIdList ?
          this.$route.query.projectIdList.split(',') : []
        const mileageList = this.$route.query.mileageList ?
          this.$route.query.mileageList.split(',') : []

        // 获取工程名称（如果有）
        this.projectNames = this.$route.query.projectNames ?
          this.$route.query.projectNames.split(',') : []
        if (this.projectNames.length >= 2) {
          // 正确更新图例数据和系列名称
          this.chartOption.legend.data = [this.projectNames[0], this.projectNames[1]]
          this.chartOption.series[0].name = this.projectNames[0]
          this.chartOption.series[1].name = this.projectNames[1]
        }

        // 请求两个工程的数据
        const requests = [
          listAll({ projectId: projectIdList[0], engineeringId: engineeringIdList[0] }),
          listAll({ projectId: projectIdList[1], engineeringId: engineeringIdList[1] })
        ]

        const [res1, res2] = await Promise.all(requests)

        // 处理工程一数据
        this.processData(res1.data, 0, parseFloat(mileageList[0] || 1))

        // 处理工程二数据
        this.processData(res2.data, 1, parseFloat(mileageList[1] || 1))

        // 初始化图表
        this.initChart()

      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取对比数据失败')
      }
    },

    // 处理数据
    processData(data, index, mileage) {
      const overallData = index === 0 ? [...this.overallData1] : [...this.overallData2]
      const intensityData = index === 0 ? [...this.intensityData1] : [...this.intensityData2]
      const barData = []

      let totalResult = 0

      // 更新各阶段数据
      for (let i = 1; i < overallData.length; i++) {
        const currentResult = data[i - 1]?.totalEmission ?
          parseFloat(data[i - 1].totalEmission.toFixed(2)) : 0

        overallData[i].value = currentResult.toString()
        barData.push(currentResult)
        totalResult += currentResult
      }

      // 更新总体数据
      overallData[0].value = `${totalResult.toFixed(2)} tCO₂e`
      intensityData[0].value = `${(totalResult / mileage).toFixed(2)} kgCO₂e/(m²·a)`

      // 更新图表数据
      this.chartOption.series[index].data = barData

      // 更新数据引用
      if (index === 0) {
        this.overallData1 = overallData
        this.intensityData1 = intensityData
      } else {
        this.overallData2 = overallData
        this.intensityData2 = intensityData
      }
    },

    // 初始化图表
    initChart() {
      const chartDom = document.getElementById('barChart');
      this.barChart = echarts.init(chartDom);
      this.barChart.setOption(this.chartOption);
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.barChart) {
        this.barChart.resize();
      }
    }
  }
}
</script>

<style scoped>
.carbon-emission-compare-container {
  padding: 20px;
  background-color: #fff;
}

.chart-container, .data-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
}

.project-title {
  text-align: center;
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

/* 调整表格样式 */
.el-table {
  font-size: 14px;
}

.el-table::before {
  height: 0;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .el-col {
    width: 100%;
  }
}
</style>
